package com.weilele.leisure.time.leancloud

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.method.ScrollingMovementMethod
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.weilele.base.library.BaseBindingDialog
import com.weilele.leisure.time.R
import com.weilele.leisure.time.databinding.DialogAppUpdateBinding
import com.weilele.leisure.time.ui.module.splash.SplashViewModel
import com.weilele.mvvm.base.livedata.appCompatActivity
import com.weilele.mvvm.base.helper.createActivityViewModel
import com.weilele.mvvm.utils.activity.*
import com.weilele.mvvm.utils.appVersionCode
import com.weilele.mvvm.utils.downloadAndInstallApk
import com.weilele.mvvm.utils.fragment.arguments
import com.weilele.mvvm.utils.installApk
import com.weilele.mvvm.utils.permission.callPermissions

class AppUpdateDialog : BaseBindingDialog<DialogAppUpdateBinding>() {
    companion object {
        fun show(appCompatActivity: AppCompatActivity, info: AVOSDb.AppInfo): Boolean {
            if (info.versionCode <= appVersionCode || (info.url.isNullOrBlank() && info.webUrl.isNullOrBlank())) {
                return false
            }
            AppUpdateDialog().apply {
                arguments {
                    putParcelable("info", info)
                }
                safeShow(appCompatActivity)
            }
            return true
        }
    }

    private val info by lazy { arguments?.getParcelable<AVOSDb.AppInfo>("info") }

    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        isCancelable = false
        mBinding.tvUpdateInfo.textFrom(info?.info)
        mBinding.tvUpdateInfo.movementMethod = ScrollingMovementMethod.getInstance()
        //判断是否必须更新
        if (info?.must == true) {
            mBinding.btSkip.textFrom("退出应用")
            mBinding.btSkip.onClick {
                finishAllActivityByList()
            }
        } else {
            mBinding.btSkip.textFrom("下次再说")
            mBinding.btSkip.onClick {
                createActivityViewModel<SplashViewModel>().loginAndGetPageData()
                dismiss()
            }
        }
        //判断是否有文件直接下载地址，没有就跳转到浏览器下载
        if (info?.url.isNullOrBlank()) {
            val webUrl = info?.webUrl
            if (!webUrl.isNullOrBlank()) {
                mBinding.btDownload.textFrom("去浏览器下载")
                mBinding.btDownload.onClick { _ ->
                    appCompatActivity?.goToBrowser(webUrl)
                }
            } else {
                dismiss()
            }
        } else {
            mBinding.btDownload.textFrom("下载")
            mBinding.btDownload.onClick { _ ->
                //安卓10以上，不在需要申请存储权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q&& !Environment.isExternalStorageLegacy()) {
                    downloadFile()
                } else {
                    callPermissions(listOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        if (it.isEmpty()) {
                            downloadFile()
                        } else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q&& !Environment.isExternalStorageLegacy()) {
                                downloadFile()
                            } else {
                                "权限拒绝。无法下载安装包".toast()
                            }
                        }
                    }
                }
            }
        }
    }

    private fun downloadFile() {
        mBinding.btDownload.isEnabled = false
        appCompatActivity?.downloadAndInstallApk(
            lifecycleScope, info!!.url!!,
            "${getResString(R.string.app_name)}_${System.currentTimeMillis()}.apk"
        ) { uri, helper ->
            helper.setOnProgressListener { current, total, progress ->
                runOnUiThread {
                    mBinding.pbDownload.visible()
                    mBinding.pbDownload.max = total.toInt()
                    mBinding.pbDownload.progress = current.toInt()
                    mBinding.btDownload.text = "下载中（${progress.toInt()}%）"
                    if (progress == 100f) {
                        mBinding.btDownload.text = "安装"
                        mBinding.btDownload.isEnabled = true
                        mBinding.btDownload.onClick {
                            appCompatActivity?.installApk(uri)
                        }
                    }
                }
            }
            helper.setOnErrorListener {
                runOnUiThread {
                    it.message.toast()
                    mBinding.tvUpdateInfo.text = it.message
                    mBinding.btDownload.text = "重试"
                    mBinding.btDownload.isEnabled = true
                    mBinding.btDownload.onClick {
                        downloadFile()
                    }
                }
            }
        }
    }
}